import 'dart:io';

import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:process_run/process_run.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/util/version.dart';

import '../../util/file_downloader.dart';

const url = 'http://teach.izis.cn/mygoedu/version.json';

class AutoUpdateController extends BaseController {
  final progress = 0.0.obs;

  var downloadUrl = '';
  String path = '';

  @override
  onInit() async {
    super.onInit();
  }

  checkUpdate() {
    var dio = Dio();
    dio.get(url).then((value) async {
      print('value:${value}');
      var version = value.data['version'];
      var localVersion = await getCurrentVersion();
      print('localVersion:${localVersion}');
      if (localVersion != version) {
        toast('发现了新版本');
        // 增量更新
        // 比较本地和服务器文件的差异,可以通过比较md5的值和文件的大小
        // 获得有差异的文件后,下载
        // 下载完成,直接覆盖现有文件
        downloadUrl = value.data['url'];
      }
    });
  }

  final downloader = FileDownloader();

  download() async {
    downloader.download(
      url: downloadUrl,
      fileName: 'setup.exe',
      onProgress: (p) {
        print('当前进度: ${(p * 100).toStringAsFixed(1)}%');
        progress.value = p;
        // if (progress.value == 1) {
        //   installUpdate(path);
        // }
      },
      onComplete: (path) {
        // print('文件下载完成: $path');
        // 开始安装或处理文件
        installUpdate(path);
      },
      onError: (error, retryCount) {
        print('错误: $error, 重试次数: $retryCount');
        if (retryCount >= 3) {}
      },
    );
  }

  installUpdate(String path) async {
    try {
      // await runExecutableArguments(path, ['/SILENT']); // 静默安装
      await Process.run(path, ['/VERYSILENT', '/SUPPRESSMSGBOXES'],
          runInShell: true);
      print('安装完成');
      // restartApp();
    } catch (e) {
      print('Failed to install update: $e');
    }
  }

  void restartApp() {
    try {
      Process.run('D:\Program Files (x86)\隐智棋盘课堂2.0.exe', []); // 新版本路径
      exit(0);
    } catch (e) {
      print('Failed to restart app: $e');
    }
  }
}
